package com.my.code.testcode.并发;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadTryLock {

    private static final Lock lock = new ReentrantLock();

    private  static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        System.out.println("hello world");
        for(int i = 0;i<3;i++){
            new Thread(() -> add()).start();
        }
    }


    public static void add(){
        for(int i= 0;i<100;i++){

            try {
                if(lock.tryLock(2, TimeUnit.SECONDS)){
                    atomicInteger.addAndGet(1);
                    System.out.println(atomicInteger+"NAME:"+Thread.currentThread().getName());
                }
            } catch (InterruptedException e) {

            }finally {
                lock.unlock();
            }


        }


    }
}
